import os
from PIL import Image
import logging

# 项目根目录
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

# 图像文件默认保存路径
DEFAULT_SAVE_PATH = os.path.join(PROJECT_ROOT, 'output')

# 支持的图像格式
SUPPORTED_FORMATS = ['.jpg', '.jpeg', '.png', '.bmp', '.gif']

# 默认的图像保存格式
DEFAULT_SAVE_FORMAT = 'jpg'

# 默认的图像尺寸
DEFAULT_IMAGE_SIZE = (800, 600)

# 默认的裁剪区域比例
DEFAULT_CROP_RATIO = (0.1, 0.9, 0.1, 0.9)  # (top, bottom, left, right)

# 默认的缩放比例
DEFAULT_SCALE_RATIO = 0.5

# 默认的旋转角度
DEFAULT_ROTATION_ANGLE = 90

# 默认的图像通道
DEFAULT_IMAGE_CHANNELS = 3

# 日志文件路径
LOG_FILE_PATH = os.path.join(PROJECT_ROOT, 'app.log')

# 日志级别
LOG_LEVEL = 'DEBUG'

# 配置日志
logging.basicConfig(filename=LOG_FILE_PATH, level=getattr(logging, LOG_LEVEL),
                    format='%(asctime)s - %(levelname)s - %(message)s')


def process_image(input_path):
    try:
        # 打开图像
        image = Image.open(input_path)

        # 裁剪图像
        width, height = image.size
        top = int(height * DEFAULT_CROP_RATIO[0])
        bottom = int(height * DEFAULT_CROP_RATIO[1])
        left = int(width * DEFAULT_CROP_RATIO[2])
        right = int(width * DEFAULT_CROP_RATIO[3])
        cropped_image = image.crop((left, top, right, bottom))

        # 缩放图像
        new_width = int(cropped_image.width * DEFAULT_SCALE_RATIO)
        new_height = int(cropped_image.height * DEFAULT_SCALE_RATIO)
        scaled_image = cropped_image.resize((new_width, new_height))

        # 旋转图像
        rotated_image = scaled_image.rotate(DEFAULT_ROTATION_ANGLE)

        # 确保保存路径存在
        if not os.path.exists(DEFAULT_SAVE_PATH):
            os.makedirs(DEFAULT_SAVE_PATH)

        # 保存图像
        file_name = os.path.basename(input_path)
        base_name, _ = os.path.splitext(file_name)
        output_path = os.path.join(DEFAULT_SAVE_PATH, f"{base_name}_processed.{DEFAULT_SAVE_FORMAT}")
        rotated_image.save(output_path)
        logging.info(f"Image processed and saved to {output_path}")
    except Exception as e:
        logging.error(f"Error processing image: {e}")


if __name__ == "__main__":
    input_image_path = 'test.jpg'  # 替换为实际的图像文件路径
    process_image(input_image_path)
    